const bcrypt = require('bcryptjs')
const SALT_WORK_FACTOR = 10


module.exports = {
    dataErrorReturn({ dataUrl, ctx,}) {
        // if (Array.isArray(dataUrl)) {
        //     ctx.body = {
        //         code: 1,
        //         result: dataUrl,
        //         success: true
        //     };
        //     return
        // }
        if (objKeys({ dataUrl }).length >= 1) {
            ctx.body = {
                code: 1,
                result: dataUrl,
                success: true
            };
        } else {
            ctx.body = {
                code: 0,
                success: false,
                message: "没有请求到数据",
                result: ""
            };
        }
    },
    JudgeAnObject({obj}) {
        return Object.keys(obj).length === 0
    },
    prosime(options) {
        let model = options.model
        let Keyword = options.Keyword
        let parameter = options.parameter
        return new Promise((resolve, reject) => {
            let obj = {
                0: {},
                1: {}
            }
            parameter.forEach((item, index) => {
                obj[index] = item
            })
            model[Keyword](obj[0], obj[1], (err, doc) => {
                if (err) {
                    reject(err)
                    return
                }
                resolve(doc)
            })
        })
    },
    forObj(obj) {
        let arr = {}
        for( let key in obj) {
            console.log(key)
            if (key !== 'password') {
                arr[key] = obj[key]
            }
        }
        return arr
    },
    pawwordBcrypt(password) {
        if (!password) return
        return new Promise((resolve, reject) => {
            bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
                if (err) {
                    reject({
                        message: '加密错误',
                        data: err
                    })
                    console.log('加密错误', err)
                    return
                }
                bcrypt.hash(password, salt, (err, hash) => {
                    if (err) {
                        reject({
                            message: '进入加密出错',
                            data: err
                        })
                        console.log('进入加密出错', err)
                        return
                    }
                    resolve(hash)
                })
            })
        })
    }
}; 

function objKeys({ dataUrl }) {
    return Object.keys(dataUrl);
}

